package streamandFile;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class DataStream {
	public static void main(String args[]) throws IOException {
		FileOutputStream fos = new FileOutputStream("d:/a.txt");
		DataOutputStream dos = new DataOutputStream(fos);
		Student[] staff = new Student[3];
		staff[0] = new Student(1, "a", 10, 1);
		staff[1] = new Student(2, "b", 11, 2);
		staff[2] = new Student(3, "c", 12, 3);
		
		try {
			//dos.writeBoolean(true);
			//dos.writeByte((byte) 123);
			//dos.writeChar('J');
			//dos.writeDouble(3.141592654);
			//dos.writeFloat(2.7182f);
			//dos.writeInt(1234567890);
			//dos.writeLong(998877665544332211L);
			//dos.writeShort((short) 11223);
			for(int i=0;i<staff.length;i++){
				writeStudent(staff[i], dos);
			}
		} finally {
			dos.close();
		}
		FileInputStream fis = new FileInputStream("d:/a.txt");
		DataInputStream dis = new DataInputStream(fis);
		
		try {
			//System.out.println("\t " + dis.readBoolean());
			//System.out.println("\t " + dis.readByte());
			//System.out.println("\t " + dis.readChar());
			//System.out.println("\t " + dis.readDouble());
			//System.out.println("\t " + dis.readFloat());
			//System.out.println("\t " + dis.readInt());
			//System.out.println("\t " + dis.readLong());
			//System.out.println("\t " + dis.readShort());
			readStudents(dis);
		} finally {
			dis.close();
		}
	}// main()201521123004
	public static void writeStudent(Student s,DataOutputStream dos) throws IOException{
		dos.writeInt(s.getId());
		dos.writeChars(s.getName());
		dos.writeInt(s.getAge());
		dos.writeDouble(s.getGrade());
	}
	public static Student[] readStudents(DataInputStream dis) throws FileNotFoundException, EOFException{
		dis= new DataInputStream(new BufferedInputStream(new FileInputStream("d:/a.txt")));
		ArrayList<Student>students=new ArrayList<>();
		try {
			while(true){
				students.add(new Student(dis.readInt(),dis.readUTF(),dis.readInt(),dis.readDouble()));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		finally{try {
			dis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}
		Student[] stu=new Student[students.size()];
		int n=0;
		for (Student s:students) {
			stu[n++]=s;	
		}
		return stu;
	}
}// class DataStream